package com.iflytek.testtoastwindow;

import android.app.ActivityManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.PowerManager;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.Toast;

import com.iflytek.testtoastwindow.utils.Reflection;

import java.util.Collection;
import java.util.List;
import java.util.UUID;
import java.util.WeakHashMap;

public class GlobalDialog implements DraggableFrameLayout.OnKeyEventListener
{
	// dialog 唯一ID
	private final String uuid = UUID.randomUUID().toString();
	private static WeakHashMap<String, GlobalDialog> showDialogs = new WeakHashMap<String, GlobalDialog>();
	private static WeakHashMap<String, GlobalDialog> pauseDialogs = new WeakHashMap<String, GlobalDialog>();
	private Toast mToast = null;
	private Object objMTN;
	private boolean mShowing = false;
	private boolean mCancelable = true;
	private boolean mTouchOutside = false;
	private DraggableFrameLayout parentView;
	private Context context = null;
	// 监听home键
	private static BroadcastReceiver homekey = null;

	public GlobalDialog(Context context) {
		context = context.getApplicationContext();
		this.context = context;
//		parentView = new ParentView(context);
        parentView = new DraggableFrameLayout(context);
		parentView.setBackgroundColor(Color.GRAY);
		parentView.setOnKeyEventListener(this);
		parentView.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,
				LayoutParams.MATCH_PARENT));
		parentView.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (mTouchOutside) {
					dismiss();
				}
			}
		});
//		synchronized (GlobalDialog.class) {
//			if (homekey == null) {
//				homekey = getHomeKeyReceiver();
//				IntentFilter filter = new IntentFilter();
//				filter.addAction(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
//				// filter.addAction(Intent.ACTION_SCREEN_OFF);
//				context.registerReceiver(homekey, filter);
//			}
//		}
		create();
	}

	// homekey 监听器
	private BroadcastReceiver getHomeKeyReceiver() {
		return new BroadcastReceiver() {
			String SYSTEM_REASON = "reason";
			String SYSTEM_HOME_KEY = "homekey";
			String SYSTEM_HOME_KEY_LONG = "recentapps";

			@Override
			public void onReceive(Context context, Intent intent) {
				String action = intent.getAction();
				if (action.equals(Intent.ACTION_CLOSE_SYSTEM_DIALOGS)) {
					String reason = intent.getStringExtra(SYSTEM_REASON);
					if (TextUtils.equals(reason, SYSTEM_HOME_KEY)) {
						// 表示按了home键,程序到了后台
						GlobalDialog.hideAll();
					} else if (TextUtils.equals(reason, SYSTEM_HOME_KEY_LONG)) {
						// 表示长按home键,显示最近使用的程序列表
						GlobalDialog.hideAll();
					}
				}
			}

		};
	}

	// 创建对话框的实例对象
	private WindowManager.LayoutParams toastParams;

	private void create() {
		try {
			mToast = new Toast(context);
			objMTN = Reflection.getProperty(mToast, "mTN");
			toastParams = (WindowManager.LayoutParams) Reflection
					.getProperty(objMTN, "mParams");
			int oriFlags = toastParams.flags;
			if (!hasFlag(oriFlags,
					WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL)) {
				 oriFlags |= WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL;
			}
			if (hasFlag(oriFlags, WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE)) {
				oriFlags ^= WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE;
			}
			if (hasFlag(oriFlags, WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE)) {
				oriFlags ^= WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;
			}
			// 赋予Toast点击事件
			toastParams.flags = oriFlags;
		} catch (Exception e1) {
			e1.printStackTrace();
		}
		try {
			objMTN = Reflection.getProperty(mToast, "mTN");
		} catch (Exception e) {

		}
		mToast.setGravity(Gravity.LEFT|Gravity.TOP, 0, 0);
		try {
			Reflection.setProperty(objMTN, "mNextView", parentView);
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (NoSuchFieldException e) {
			e.printStackTrace();
		}
	}

	public View findViewById(int id) {
		return parentView.findViewById(id);
	}

	public Context getContext() {
		return context;
	}

	private boolean hasFlag(int flags, int flag) {
		return (flags & flag) > 0;
	}

	public boolean isShowing() {
		return mShowing;
	}

	public void setCanceledOnTouchOutside(boolean cancel) {
		this.mTouchOutside = cancel;
	}

	public void setCancelable(boolean flag) {
		this.mCancelable = flag;
	}

	public void show() {
		synchronized (this) {
			if (mShowing) {
				return;
			}
			if (mShow()) {
				showDialogs.put(uuid, GlobalDialog.this);
				showDialogs.size();
				mShowing = true;
			}
		}

	}

	public void dismiss() {
		synchronized (this) {
			if (!mShowing) {
				return;
			}
			if (mHide()) {
				showDialogs.remove(uuid);
				mShowing = false;
			}
		}
	}

	// 显示布局
	private boolean mShow() {
		try {
			// parentView.setVisibility(View.VISIBLE);
			Reflection.invokeMethod(objMTN, "handleShow", null, null);
			return true;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}

	// 隐藏布局
	private boolean mHide() {
		try {
			// parentView.setVisibility(View.GONE);
			Reflection.invokeMethod(objMTN, "handleHide", null, null);
			return true;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}

	// 设置显示布局
	public void setContentView(View v) {
		parentView.addView(v);
	}

	public void setContentView(int layoutId) {
		LayoutInflater.from(context).inflate(layoutId, parentView);
	}

	// 回复全局对话框
	public synchronized static void callRemase(Context context) {
		if (pauseDialogs.size() == 0)
			return;
		Collection<GlobalDialog> coll = pauseDialogs.values();
		for (GlobalDialog dialog : coll) {
			if (dialog != null)
				dialog.mShow();
		}
		pauseDialogs.clear();
	}

	public synchronized static void callPause(Context context) {
		PowerManager manager = (PowerManager) context
				.getSystemService(Context.POWER_SERVICE);
		if (!manager.isScreenOn()) {
			Collection<GlobalDialog> coll = showDialogs.values();
			for (GlobalDialog dialog : coll) {
				if (dialog != null)
					dialog.mHide();
			}
			pauseDialogs.clear();
			pauseDialogs.putAll(showDialogs);
		}
	}

	// 销毁正在显示的对话框
	public synchronized static void callStop(Context context) {
		if (showDialogs.size() == 0)
			return;
		if (isBackground(context)) {
			Collection<GlobalDialog> coll = showDialogs.values();
			for (GlobalDialog dialog : coll) {
				if (dialog != null)
					dialog.mHide();
			}
			pauseDialogs.clear();
			pauseDialogs.putAll(showDialogs);
		}

	}

	private synchronized static void hideAll() {
		Collection<GlobalDialog> coll = showDialogs.values();
		for (GlobalDialog dialog : coll) {
			if (dialog != null)
				dialog.mHide();
		}
		pauseDialogs.clear();
		pauseDialogs.putAll(showDialogs);
	}

	/**
	 * 检测APP是否已经后台
	 * */
	public static boolean isBackground(Context context) {
		ActivityManager activityManager = (ActivityManager) context
				.getSystemService(Context.ACTIVITY_SERVICE);
		List<ActivityManager.RunningAppProcessInfo> appProcesses = activityManager
				.getRunningAppProcesses();
		for (ActivityManager.RunningAppProcessInfo appProcess : appProcesses) {
			if (appProcess.processName.equals(context.getPackageName())) {
				/*
				 * BACKGROUND=400 EMPTY=500 FOREGROUND=100 GONE=1000
				 * PERCEPTIBLE=130 SERVICE=300 ISIBLE=200
				 */
				// Log.i(context.getPackageName(), "此appimportace ="
				// + appProcess.importance
				// + ",context.getClass().getName()="
				// + context.getClass().getName());
				if (appProcess.importance != ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
					// Log.i(context.getPackageName(), "处于后台"
					// + appProcess.processName);
					return true;
				} else {
					// Log.i(context.getPackageName(), "处于前台"
					// + appProcess.processName);
					return false;
				}
			}
		}
		return false;
	}

	public class ParentView extends FrameLayout {

		public ParentView(Context context) {
			super(context);
		}

		@Override
		public boolean dispatchKeyEvent(KeyEvent event) {
			switch (event.getAction()) {
			case KeyEvent.ACTION_DOWN:
				GlobalDialog.this.onKeyDown(event.getKeyCode(), event);
				break;
			case KeyEvent.ACTION_UP:
				GlobalDialog.this.onKeyUp(event.getKeyCode(), event);
				break;
			default:
				break;
			}
			return super.dispatchKeyEvent(event);
		}
	}

	public boolean onKeyDown(int keyCode, KeyEvent event) {
		return false;
	}

	public boolean onKeyUp(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			onBackPressed();
			return true;
		}
		return false;
	}

	public void onBackPressed() {
		if (isShowing() && mCancelable) {
			dismiss();
		}
	}
}
